<?php
/**
 * User: xuxiaoming
 * Date: 2017/11/7
 * Time: 17:55
 */

namespace App\Http\Controllers;


use App\Models\Oauth;
use App\Models\User;
use App\Models\UserProject;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller;

class OauthController extends Controller
{
    /**
     * @var int 权限令牌过期时间
     */
    private $_accessTokenExpire = 21600000;

    /**
     * @var int 刷新令牌过期时间
     */
    private $_refreshTokenExpire = 259200000;


    /**
     * 列表
     * @param Request $request
     * @return string
     */
    public function getToken(Request $request)
    {
        //判断email
        if (!$request->has("email")) {
            return sendJsonMessage("email必须填写", true);
        }
        //判断password
        if (!$request->has("password")) {
            return sendJsonMessage("password必须填写", true);
        }
        $user = User::where([
            "email" => $request->get("email"),
            "password" => $request->get("password"),
        ])->get()->first();
        if (!$user) {
            return sendJsonMessage('用户不能存在或密码错误', true);
        }
        $token = $this->_genToken($user->id);
        return sendJsonData($token);
    }


    /**
     * 生成Token
     * @param $userId
     * @return array
     */
    protected function _genToken($userId)
    {
        //权限令牌过期时间
        $accessTokenExpireTimestamp = $_SERVER['REQUEST_TIME'] + $this->_accessTokenExpire;

        $token = Oauth::where(["user_id" => $userId])->where("access_token_expire", ">",date("Y-m-d H:i:s"))
            ->get()->first();
        if ($token) {
            return $token->toArray();
        }
        //权限令牌
        $accessToken = sha1(uniqid('', TRUE) . mt_rand());

        //刷新令牌
        $refreshToken = sha1(uniqid('', TRUE) . mt_rand());
        //刷新令牌过期时间
        $refreshTokenExpireTimestamp = $_SERVER['REQUEST_TIME'] + $this->_refreshTokenExpire;
        //令牌数据
        $data = [
            "user_id" => $userId,
            "access_token" => $accessToken,
            "access_token_expire" => date("Y-m-d H:i:s", $accessTokenExpireTimestamp),
            "refresh_token" => $refreshToken,
            "refresh_token_expire" => date("Y-m-d H:i:s", $refreshTokenExpireTimestamp)
        ];
        Oauth::create($data);
        //返回数据
        return $data;
    }


}